<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

<head>
	<th:block th:include="include :: header('素材列表')" />
	<th:block th:include="include :: layout-latest-css" />
	<th:block th:include="include :: ztree-css" />
</head>

<body class="gray-bg">
	<div class="ui-layout-west">
		<div class="box box-main">
			<div class="box-header">
				<div class="box-title">
					<i class="fa icon-grid"></i> 素材分组
				</div>
				<div class="box-tools pull-right">
					<button type="button" class="btn btn-box-tool" onclick="addGroup()">
						<i class="fa fa-plus"></i>
					</button>
					<button type="button" class="btn btn-box-tool" onclick="editGroup()">
						<i class="fa fa-edit"></i>
					</button>
					<button type="button" class="btn btn-box-tool" onclick="queryGroupTree()">
						<i class="fa fa-refresh"></i>
					</button>
					<button type="button" class="btn btn-box-tool" onclick="delGroup()">
						<i class="fa fa-trash"></i>
					</button>
				</div>
			</div>
			<div class="ui-layout-content">
				<div id="tree" class="ztree"></div>
			</div>
		</div>
	</div>
	<div class="ui-layout-center">
		<div class="container-div">
			<div class="row">
				<div class="col-sm-12 search-collapse">
					<div class="nav-tabs-custom">
						<ul class="nav nav-tabs">
							<li class="active"><a data-toggle="tab" aria-expanded="true"
									onclick="setMaterialType('')">全部</a></li>
							<li><a data-toggle="tab" aria-expanded="false" onclick="setMaterialType('1')">图片</a></li>
							<li><a data-toggle="tab" aria-expanded="false" onclick="setMaterialType('2')">视频</a></li>
						</ul>
					</div>
				</div>
				<div class="btn-group-sm" id="toolbar" role="group" style="width: 980px;">
					<form id="formId" action="">
						<input type="hidden" id="groupId" name="groupId"> <input type="hidden" id="materialType"
							name="materialType">
						<div class="row">
							<div class="col-sm-12">
								<div class="select-list">
									<ul>
										<li>
											<a class="btn btn-success btn-sm" onclick="selectImages()">
												<i class="fa fa-cloud-upload"></i> 上传
											</a>
											<input type="file" id="imageUpload" name="file" style="display:none"
												accept="image/*" onchange="uploadMaterials()" multiple="multiple">
											<a class="btn btn-primary btn-sm" onclick="selectGroupTree()">
												<i class="fa fa-exchange"></i> 移动
											</a>
										<li>
										<li>
											<div class="input-group" style="width: 330px;">
												<div class="input-group-addon">名称</div>
												<input class="form-control" type="text" id="materialName"
													name="materialName"> <span class="input-group-btn">
													<a class="btn btn-white btn-sm" onclick="$.table.search()"><i
															class="fa fa-search"></i>&nbsp;搜索</a>
												</span> <span class="input-group-btn"> <a class="btn btn-white btn-sm"
														onclick="reset()"><i class="fa fa-refresh"></i> 重置</a>
												</span>
											</div>
										</li>
									</ul>
								</div>
							</div>
						</div>
					</form>
				</div>
				<div class="col-sm-12 select-table table-striped">
					<table id="bootstrap-table"> </table>
				</div>
			</div>
		</div>
		<template id="profileTemplate">
			<div class="col-sm-2">
				<div class="ibox">
					<div class="ibox-content">
						<img alt="image" class=" m-t-xs img-responsive" src="%IMAGE%">
						<div class="text-center">
							<div class="checkbox">
								<label class="inline"> <input type="checkbox" onblur="" name="check"
										value="%materialId%"> <a class="btn btn-xs btn-success"><i
											class="fa fa-check"></i>
										选择</a>
								</label> <a class="btn btn-xs btn-danger" onclick=""><i class="fa fa-remove"></i> 删除</a>
							</div>
						</div>
					</div>
				</div>
			</div>
		</template>
	</div>
	<th:block th:include="include :: footer" />
	<th:block th:include="include :: bootstrap-table-custom-view-js" />
	<th:block th:include="include :: layout-latest-js" />
	<th:block th:include="include :: ztree-js" />
	<script th:inline="javascript" type="text/javascript">
		var prefix = ctx + "shop/material";
		var selectNodeId = 0;
		var materialTypes = [[${@dict.getType('shop_material_type')}]];
		var datas = [[${@dict.getType('shop_enable_status')}]];
		$(function () {
			var panehHidden = false;
			if ($(this).width() < 769) {
				panehHidden = true;
			}
			$('body').layout({initClosed: panehHidden, west__size: 185});
			// 回到顶部绑定
			if ($.fn.toTop !== undefined) {
				var opt = {
					win: $('.ui-layout-center'),
					doc: $('.ui-layout-center')
				};
				$('#scroll-up').toTop(opt);
			}
			queryMaterialList();
			queryGroupTree();
			$("button[name='customView']").click();//默认列表
		});

		/**左侧功能 **/
		function queryGroupTree() {
			var url = ctx + "shop/material/group/treeData/0";
			var options = {
				url: url,
				expandLevel: 2,
				onClick: zOnClick
			};
			$.tree.init(options);
			function zOnClick(event, treeId, treeNode) {
				$("#groupId").val(treeNode.id);
				$.table.search();
			}
		}
		function addGroup() {
			layer.prompt({title: '请输入新分组名称', formType: 0}, function (itemName, index) {
				$.operate.submit(prefix + "/group/add", "post", "json", {groupName: itemName}, function (res) {
					if (res.code == web_status.SUCCESS) {
						layer.close(index);
						queryGroupTree();
					} else {
						$.modal.alertError(res.msg);
					}
				});
			});
		}
		function editGroup() {
			if ($.common.isEmpty($("#groupId").val())) {
				$.modal.alertWarning("请选择一条记录");
				return "";
			}
			layer.prompt({title: '请输入新分组名称', formType: 0}, function (itemName, index) {
				$.operate.submit(prefix + "/group/edit", "post", "json", {groupId: $("#groupId").val(), groupName: itemName}, function (res) {
					if (res.code == web_status.SUCCESS) {
						layer.close(index);
						queryGroupTree();
					} else {
						$.modal.alertError(res.msg);
					}
				});
			});
		}
		function delGroup() {
			if ($.common.isEmpty($("#groupId").val())) {
				$.modal.alertWarning("请选择一条记录");
				return "";
			}
			$.modal.confirm("确定删除该分组吗？", function () {
				$.operate.submit(prefix + "/group/remove/" + $("#groupId").val(), "get", "json", function (res) {
					layer.close(index);
				});
				queryGroupTree();
			});
		}
		/**右侧功能 **/
		function queryMaterialList() {
			var options = {
				url: prefix + "/list",
				createUrl: prefix + "/add/{id}",
				updateUrl: prefix + "/edit/{id}",
				showSearch: false,
				showRefresh: false,
				showToggle: false,
				showColumns: false,
				modalName: "素材",
				uniqueId: 'materialId',
				columns: [{
					radio: true
				},
				{
					field: 'materialId',
					title: '素材ID',
					visible: false
				},
				{
					field: 'materialName',
					title: '名称',
					align: 'center'
				},
				{
					field: 'materialType',
					title: '类型',
					align: 'center',
					formatter: function (value, row, index) {
						return $.table.selectDictLabel(materialTypes, value);
					}
				},
				{
					field: 'url',
					title: '缩略图',
					align: 'center',
					formatter: function (value, row, index) {
						if (row.materialType == 1) {//如果是图片
							return "<img src='" + value + "' style='width:30px;height:30px;' target='_blank' title='点击查看' onclick='imagePreview(\"" + value + "\")'></img>";
						} else {
							return "";
						}
					}
				},
				{
					field: 'groupName',
					title: '所属分组',
					align: 'center'
				},
				{
					field: 'size',
					title: '大小',
					align: 'center',
					formatter: function (value, row, index) {
						return renderFileSize(value);
					}
				},
				{
					field: 'createTime',
					title: '上传时间',
					align: 'center'
				},
				{
					title: '操作',
					align: 'center',
					formatter: function (value, row, index) {
						var actions = [];
						actions.push('<a class="btn btn-success btn-xs"  onclick="toEditMaterial(' + row.materialId + ')"><i class="fa fa-edit"></i>编辑</a> ');
						actions.push('<a class="btn btn-danger  btn-xs"  onclick="delMaterial(' + row.materialId + ')"><i class="fa fa-remove"></i>删除</a>');
						return actions.join('');
					}
				}]
			};
			$.table.init(options);
		}
		/**打开分组树*/
		function selectGroupTree() {
			var selectedIds = getselectedIds();
			if (selectedIds != "") {
				var options = {
					title: '选择分组',
					width: "380",
					url: prefix + "/group/selectGroupTree/0/0",
					callBack: doSubmit
				};
				$.modal.openOptions(options);
			}
		}
		/**移动到选中分组**/
		function doSubmit(index, layero) {
			var body = $.modal.getChildFrame(index);
			var groupId = body.find('#treeId').val();
			var materialIds = getselectedIds();
			$.modal.confirm("确认要修改分组吗？", function () {
				$.operate.post(prefix + "/changeGroup/", {"materialIds": materialIds, "groupId": groupId}, function (res) {
					if (res.code == web_status.SUCCESS) {
						$.modal.close(index);
						queryMaterialList();
					} else {
						$.modal.alertError(res.msg);
					}
				});
			});
		}
		/**获取选中的数据id**/
		function getselectedIds() {
			var selectedIds = "";
				var rows = $.table.selectFirstColumns();
				if (rows.length == 0) {
					$.modal.alertWarning("请至少选择一条记录");
					return "";
				}
				selectedIds = rows.join();
			return selectedIds;
		}
		/**删除素材id**/
		function delMaterial(materialId) {
			$.modal.confirm("确定删除该素材吗？", function () {
				$.operate.get(ctx + "shop/material/remove/" + materialId, function (res) {
					queryMaterialList();
				});
			});
		}
		function selectImages() {
			$("#imageUpload").click();
		}
		//上传素材
		function uploadMaterials() {
			var formData = new FormData();
			var files = $("#imageUpload").prop("files")
			for (var i = 0; i < files.length; i++) {
				formData.append("files", files[i]);
			}
			var groupId = $("#groupId").val() == "" ? 1 : $("#groupId").val();
			formData.append("groupId", groupId);
			$.ajax({
				url: prefix + "/uploadMaterials",
				dataType: 'json',
				type: 'post',
				data: formData,
				cache: false,
				processData: false,
				contentType: false,
				success: function (result) {
					if (result.code == web_status.SUCCESS) {
						layer.msg("操作成功,正在刷新数据请稍后……", {
							icon: 1,
							time: 500,
							shade: [0.1, '#8F8F8F']
						}, function () {
							$.table.search();
						});
					} else {
						$.modal.alertError(result.msg);
					}
				}
			})
		}
		function search() {
			if ($("#materialName").val().length > 0) {
				$("#categoryId").val("");
			}
			$.table.search();
		}
		function reset() {
			$("#materialName").val("");
			$("#groupId").val("");
			$.table.search();
			var treeObj = $.fn.zTree.getZTreeObj("tree");
			treeObj.cancelSelectedNode();
		}

		function tooltip(str, len) {
			//length属性读出来的汉字长度为1
			if (str.length * 2 <= len) {
				return str;
			}
			var strlen = 0;
			var s = "";
			for (var i = 0; i < str.length; i++) {
				s = s + str.charAt(i);
				if (str.charCodeAt(i) > 128) {
					strlen = strlen + 2;
					if (strlen >= len) {
						return s.substring(0, s.length - 1) + "...";
					}
				} else {
					strlen = strlen + 1;
					if (strlen >= len) {
						return s.substring(0, s.length - 2) + "...";
					}
				}
			}
			return s;
		}
		/* 素材管理-分组 */
		function group() {
			var url = ctx + "shop/material/group";
			$.modal.openTab("素材分组", url);
		}

		//  格式化文件大小
		function renderFileSize(value) {
			if (null == value || value == '') {
				return "0 Bytes";
			}
			var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
			var index = 0,
				srcsize = parseFloat(value);
			index = Math.floor(Math.log(srcsize) / Math.log(1024));
			var size = srcsize / Math.pow(1024, index);
			//  保留的小数位数
			size = size.toFixed(2);
			return size + unitArr[index];
		}

		function imagePreview(url) {
			layer.photos({
				photos: {
					"data": [{
						"src": url
					}]
				}
			});
		}

		function setMaterialType(materialType) {
			$("#materialType").val(materialType);
			$.table.search();
		}


		/**获取选中的数据id**/
		function getSelections() {
			var selectId = "";
			if ($("#bootstrap-table").css("display") == "none") {//平铺模式
				if ($("input[name='materialcheck']:checked").length == 0) {
					$.modal.alertWarning("请选择一条记录");
					return "";
				}
				selectId = $("input[name='materialcheck']:checked").val();

			} else {//列表模式
				var rows = $.table.selectFirstColumns();
				if (rows.length == 0) {
					$.modal.alertWarning("请选择一条记录");
					return "";
				}
				selectId = rows[0];
			}
			if (selectId != "") {
				return $('#bootstrap-table').bootstrapTable('getRowByUniqueId', selectId).url;
			}
			return selectId;
		}
	</script>
</body>

</html>